package com.bluno.connection;

import java.io.IOException;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;

@TargetApi(7)
public class ConnectThread extends Thread{

	private BluetoothSocket socket;
	private BluetoothDevice device;
	private ConnManager manager;
	
	public ConnectThread(ConnManager manager, BluetoothDevice device) {
		this.manager = manager;
		this.device = device;
		BluetoothSocket tmp = null;
		try {
			tmp = device.createRfcommSocketToServiceRecord(ConnManager.MY_UUID);
		}catch(IOException e) {
		}
		this.socket = tmp;
	}
	
	public void run() {
		
		setName("ConnectThread");
		// Always cancel discovery because it will slow down a connection
		//manager.getBtAdapter().cancelDiscovery();
		
		try {
			socket.connect();
		}catch(IOException e) {
			//connectionFailed();
			try {
				socket.close();
			} catch(IOException e2) {
				//log unable to close socket
			}
				manager.getConnectThread().start();
			return;
		}
		synchronized (manager.getConnectThread()) {
			manager.setConnectThread(null);
		}
		//Pega o socket aqui!!!
		manager.connected(socket);		
	}
	
	public void cancel() {
        try {
            socket.close();
        } catch (IOException e) {
            //failed to close socket
        }
    }
	
}